/**
 * 19. 删除链表的倒数第 N 个结点
 * https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
 */
const { displayListNode, createListNode } = require('../../libs/public');

const cache = new Array(30);

/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
function removeNthFromEnd(head, n) {
  let length = 0;
  let cur = head;
  while (cur) {
    cache[length] = cur;
    cur = cur.next;
    length += 1;
  }
  const index = length - n;
  if (index === 0) {
    return head.next;
  } if (n === 1) {
    cache[index - 1].next = null;
    return head;
  }
  cache[index - 1].next = cache[index + 1];
  return head;
}

console.log(displayListNode(removeNthFromEnd(createListNode([1, 2, 3, 4, 5]), 2)) === '[1,2,3,5]');
console.log(displayListNode(removeNthFromEnd(createListNode([1]), 1)) === '[]');
